package com.beamfield.controller.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.beamfield.common.CommonUtils;
import com.beamfield.common.TokenManage;
import com.beamfield.enums.HttpResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author Zephyr
 * @Description:
 * @Date 2018/10/9
 */
public class TokenInterceptorAdapter extends HandlerInterceptorAdapter {

    public TokenInterceptorAdapter() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        if(LocalDateTime.now().isAfter(LocalDateTime.of(2019, 3, 15, 23, 0))){
//            return false;
//        }
        JSONObject jsonObj = CommonUtils.getJsonObject(request);
        String token = request.getParameter("token");
        if (jsonObj != null) {

            if (jsonObj.containsKey("body")) {
                request.setAttribute("body", jsonObj.get("body"));
            }

            token = jsonObj.getString("token");
        }
        request.setAttribute("token", token);
        if (StringUtils.isNotEmpty(token) && TokenManage.isRight(token)) {
            return true;
        } else {
            OutputStream out = response.getOutputStream();
            response.setContentType("text/html");
            JSONObject json = new JSONObject();
            json.put("code", HttpResultEnum.TOKEN_FAILURE.getCode());
            json.put("message", HttpResultEnum.TOKEN_FAILURE.getMessage());
            out.write(json.toString().getBytes());
            out.close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
